﻿#region Header File
//
// MeanVar.cs - Mean and Variance Estimation
//
// Copyright (C) Javier Valcarce. BSD License
#endregion


namespace Arq
{

    /// <summary>
    /// Statistical estimator of mean and variance 
    /// </summary>
    public class MeanVar
    {
        double m = 0; // mean
        double v = 0; // var
        long   n = 0; // sample count
        double t;

        double max = double.NegativeInfinity;
        double min = double.PositiveInfinity;
        
        /// <summary>
        /// Compute a new sample and update estimators
        /// </summary>
        /// <param name="s"></param>
        public void Compute(double s)
        {
            n++;

            m = m * (n - 1) / n + s / n;
            t = (s - m) * (s - m);
            v = v * (n - 1) / n + t / n;

            if (s > max) max = s;
            if (s < min) min = s;
        }


        /// <summary>
        /// Resets internal state
        /// </summary>
        public void Reset()
        {
            m = v = 0;
            n = 0;
        }

        // properties
        public double Mean     { get { return m; } }
        public double Variance { get { return v; } }
        public double Count    { get { return n; } }
        public double Max      { get { return max; } }
        public double Min      { get { return min; } }
    }
}